package com.tongtech.system.controller;

import com.tongtech.common.core.utils.CryptoUtil;
import com.tongtech.common.core.web.controller.BaseController;
import com.tongtech.common.core.web.domain.AjaxResult;
import com.tongtech.common.core.web.page.TableDataInfo;
import com.tongtech.common.log.annotation.Log;
import com.tongtech.common.log.enums.BusinessType;
import com.tongtech.common.security.annotation.RequiresPermissions;
import com.tongtech.common.security.utils.SecurityUtils;
import com.tongtech.system.domain.File;
import com.tongtech.system.enums.FileWorkSpaceType;
import com.tongtech.system.service.IFileService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * 文件信息
 *
 * @author xingyc
 */
@RestController
@RequestMapping("/file")
public class FileController extends BaseController
{
    @Autowired
    private IFileService fileService;

    /**
     * 获取文件列表
     */

    @RequiresPermissions("file:info:list")
    @GetMapping("/list")
    public TableDataInfo list(File file)
    {
        startPage();
        Byte workspace = file.getWorkspace();
        List<File> list = null;
        //判断查询公共数据，还是私有数据
        if(FileWorkSpaceType.PUBLIC.getCode().equals(workspace)){
            list = fileService.selectPublicFileList(file);
        }else{
            list = fileService.selectFileList(file);
        }
        return getDataTable(list);
    }

//    /**
//     * 获取文件列表
//     */
//    @RequiresPermissions("file:info:list")
//    @PostMapping("/download")
//    public void download(@RequestBody File file, HttpServletResponse response)  {
//        try {
//            String fileIdStr = file.getFileIdStr();
//            if(StringUtils.isNotEmpty(fileIdStr)){
//                fileIdStr = CryptoUtil.decrypt(fileIdStr);
//                Long fileId = Long.valueOf(fileIdStr);
//                fileService.download(fileId, response);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 获取文件列表
     * TODO 为后续下载预留接口
     */
    @RequiresPermissions("file:info:list")
    @PostMapping("/download")
    public void downloadFromMinio(@RequestBody File file, HttpServletResponse response)  {
        try {
            InputStream inputStream = fileService.downloadFromMinio(1L, response);
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8"));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    /**
     * 根据文件编号获取详细信息
     */
    @RequiresPermissions("file:info:query")
    @GetMapping(value = "/{fileId}")
    public AjaxResult getInfo(@PathVariable Long fileId)
    {
        return success(fileService.selectFileById(fileId));
    }

    /**
     * 新增文件
     */
    @RequiresPermissions("file:info:add")
    @Log(title = "文件管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody File file)
    {
       if(Objects.nonNull(file)){
           file.setCreateBy(SecurityUtils.getUsername());
       }
        return success(fileService.insertFile(file));
    }

    /**
     * 批量新增文件
     */
    @RequiresPermissions("file:info:add")
    @Log(title = "文件管理", businessType = BusinessType.INSERT)
    @PostMapping("/insertBatch")
    public AjaxResult insertBatch(@RequestBody List<File> files)
    {
        int count = 0;
        if(!CollectionUtils.isEmpty(files)){
            count = fileService.insertFileBatch(files);
        }
        return toAjax(count);
    }

    /**
     * 修改文件
     */
    @RequiresPermissions("file:info:edit")
    @Log(title = "文件管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody File file)
    {
        if(Objects.nonNull(file)){
            file.setUpdateBy(SecurityUtils.getUsername());
        }
        return toAjax(fileService.updateFile(file));
    }

    /**
     * 删除文件
     */
    @RequiresPermissions("file:info:remove")
    @Log(title = "文件管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{fileId}")
    public AjaxResult remove(@PathVariable Long fileId)
    {
        return toAjax(fileService.deleteFileById(fileId));
    }
}
